package com.jdcjk.project.main.view;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jdcjk.Constant;
import com.jdcjk.MainApp;
import com.jdcjk.R;
import com.jdcjk.UrlAddress;
import com.jdcjk.base.presenter.BasePresenter;
import com.jdcjk.base.view.BaseFragment;
import com.jdcjk.chat.enity.MessageBean;
import com.jdcjk.project.account.model.entity.Result;
import com.jdcjk.project.car.view.CarActivity;
import com.jdcjk.project.main.model.adapter.TextWatcherAdapter;
import com.jdcjk.project.main.model.entity.CarListInfo;
import com.jdcjk.project.main.model.entity.TerminalInfoListResult;
import com.jdcjk.project.main.presenter.MainPresenter;
import com.jdcjk.util.PreferencesUtils;
import com.jdcjk.util.SearchEditTextUtil;
import com.jdcjk.view.RefreshLayout;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by dong on 2016/12/9.
 * 车辆列表
 */
public class CarListFragment extends BaseFragment<MainPresenter> {
    private final String TAG = CarListFragment.class.getSimpleName();
    private ViewGroup withoutCarInfo_viewGroup;
    private ListView carList_listView;
    //支持上拉下拉刷新的布局
    private RefreshLayout carList_refreshlayout;
    private MainPresenter presenter;
    private EditText searchCar_editText;
    private CarListFragmentAdapter adapter;
    private List<CarListInfo> carListInfoList = new ArrayList<>();
    //查询button
    private ImageButton fragmentCarSearch_button;

    //用户账号
    private String account;
    //添加设备按钮
    private ImageButton fragmentCarAdd_button;
    //搜索不到设备时显示的textview
    private TextView cantFindCar_textView;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_car_list;
    }

    @Override
    public MainPresenter bindPresenter() {
        presenter = new MainPresenter(getContext());
        return presenter;
    }

    @Override
    public void initContentView(View viewContent) {
        // 初始化控件
        withoutCarInfo_viewGroup = (ViewGroup) viewContent.findViewById(R.id.fragment_car_list_without_car_info);
        carList_listView = (ListView) viewContent.findViewById(R.id.fragment_car_list_lv);
        searchCar_editText = (EditText) viewContent.findViewById(R.id.fragment_car_list_search_car_et);
        fragmentCarAdd_button = (ImageButton) viewContent.findViewById(R.id.fragment_car_add_btn);
        fragmentCarSearch_button = (ImageButton) viewContent.findViewById(R.id.fragment_car_search_btn);
        fragmentCarSearch_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchCar_editText.requestFocus();
                //调用系统输入法
                InputMethodManager imm = (InputMethodManager) searchCar_editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(searchCar_editText, 0);
            }
        });
        cantFindCar_textView = (TextView) viewContent.findViewById(R.id.cant_find_car_tv);
        // 设置文本监听
        setWatchTextListener();

        fragmentCarAdd_button.setOnClickListener(this);
        carList_refreshlayout = (RefreshLayout) viewContent.findViewById(R.id.fragment_car_list_refreshlayout);
        //设置上下拉刷新
        swipeRefreshLayoutSet();
    }

    @Override
    public void refreshView() {
        super.refreshView();
        // 获取数据
        account = PreferencesUtils.getString(getActivity(), Constant.UserInfo.account);
        //获取用户设备列表
        presenter.getTerminalForUser(UrlAddress.GET_TERMINAL_FOR_USER, account, new BasePresenter.OnUIThreadListener<TerminalInfoListResult>() {
            @Override
            public void onBefore(Request request, int id) {
            }

            @Override
            public void onAfter(int id) {
                //清除下拉刷新加载
                carList_refreshlayout.setRefreshing(false);
            }

            @Override
            public void onError(Call call, Exception e, int i) {
                Toast.makeText(getActivity(), R.string.system_exception, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(TerminalInfoListResult result) {
                switch (result.getStatus()) {
                    case "OK":
                        //终端列表信息
                        carListInfoList = result.getResult();
//                        //坐标切换
//                        for (int i = 0; i < carListInfoList.size(); i++) {
//                            LatLng latLng = new LatLng(carListInfoList.get(i).getLatitude(), carListInfoList.get(i).getLongitude());
//                            latLng = GaoDeMapUtil.gaodeLatLngEncrypt(latLng);
//                            carListInfoList.get(i).setLatLng(latLng.latitude, latLng.longitude);
//                        }
                        adapter = new CarListFragmentAdapter(carListInfoList);
                        carList_listView.setAdapter(adapter);
                        refreshUI(carListInfoList);
                        break;
                    case "FAILED":
                        adapter = new CarListFragmentAdapter(new ArrayList<CarListInfo>());
                        refreshUI(new ArrayList<CarListInfo>());
                        break;
                }
            }
        });
    }

    public void updataCarInfo(final MessageBean.TerminalStatusBean terminalStatusBean) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < carListInfoList.size(); i++) {
                    //判断状态变化的车辆id
                    if (terminalStatusBean.getId() == carListInfoList.get(i).getId()) {
                        //刷新车辆的数据，并刷新显示
                        carListInfoList.get(i).setOnline(terminalStatusBean.isOnline());
                        carListInfoList.get(i).setDisplayid(terminalStatusBean.getDisplayid());
                        Message msg = new Message();
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }
                }
            }
        }).start();
    }

    /**
     * 关闭当前所有设备
     */
    public void closeAllTerminal() {
        for (int i = 0; i < carListInfoList.size(); i++) {
            //刷新车辆的数据，并刷新显示
            carListInfoList.get(i).setOnline(false);
            carListInfoList.get(i).setAcc(false);
            Message msg = new Message();
            msg.what = 1;
            handler.sendMessage(msg);
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                //刷新当前list
                adapter.notifyDataSetChanged();
            }
        }
    };

    private void swipeRefreshLayoutSet() {
        carList_refreshlayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_blue_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        // 下拉刷新
        carList_refreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //显示下拉刷新加载
                        carList_refreshlayout.setRefreshing(true);
                        refreshView();
                        searchCar_editText.setText("");
                    }
                }, 400);
            }
        });
        // 上拉刷新
//        carList_refreshlayout.setOnLoadListener(new RefreshLayout.OnLoadListener() {
//
//            @Override
//            public void onLoad() {
//
//                carList_refreshlayout.postDelayed(new Runnable() {
//
//                    @Override
//                    public void run() {
//                       carList_refreshlayout.setLoading(false);
//                    }
//                }, 1500);
//
//            }
//        });
    }

    /**
     * 获得车辆列表list
     *
     * @return
     */
    public List<CarListInfo> getCarInfoList() {
        return carListInfoList;
    }

    private void setWatchTextListener() {
        // 根据输入框输入值的改变来过滤搜索
        searchCar_editText.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                // filterData(s.toString());
                if (!TextUtils.isEmpty(s)) {
                    adapter.setSearchingString(s.toString());
                    searchList(s.toString());
                } else {// 如果输入框内容为空，显示全部
                    adapter.setSearchingString("");
                    searchList("");
                }
            }
        });
    }

    private static int lastest = 0;

    // 实现线程同步搜索联系人
    // 线程同步问题可能会导致数据显示错误，比如会显示上一次搜索到的数据
    public void searchList(final String s) {
        // 用户可能正在快速输入电话号码，之前在搜索的联系人列表已经过时了。
        final int i = ++lastest;
        // 开一个线程来进行快速搜索
        new Thread(new Runnable() {

            @Override
            public void run() {
                List<CarListInfo> filterDateList;
                if (TextUtils.isEmpty(s)) {
                    // 如果输入的字符串为空，则显示所有联系人
                    filterDateList = carListInfoList;
                } else {
                    // searhContacts指向搜索返回的list
                    filterDateList = SearchEditTextUtil.search(s, carListInfoList);
                }
                if (i == lastest) { // 避免线程同步问题
                    final List<CarListInfo> finalFilterDateList = filterDateList;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (i == lastest) { // 避免线程同步问题
                                if (finalFilterDateList.size() > 0 || s.equals("")) {
                                    refreshList(finalFilterDateList);
                                    cantFindCar_textView.setVisibility(View.GONE);
                                    carList_listView.setVisibility(View.VISIBLE);
                                } else {
                                    //只有当有输入时才会显示找不到车辆
                                    cantFindCar_textView.setVisibility(View.VISIBLE);
                                    carList_listView.setVisibility(View.GONE);
                                }
                            }
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 解除设备绑定
     *
     * @param snNum 设备id
     */
    private void unbindTerminal(String snNum, final int position) {
        //解绑确定按钮监听
        presenter.unbindTerminal(UrlAddress.UNBIND_TERMINAL_FOR_USER, account, snNum, new BasePresenter.OnUIThreadListener<Result>() {
            @Override
            public void onBefore(Request request, int id) {

            }

            @Override
            public void onAfter(int id) {

            }

            @Override
            public void onError(Call call, Exception e, int i) {

            }

            @Override
            public void onResponse(Result result) {
                switch (result.getStatus()) {
                    case "OK":
                        Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
                        adapter.removeItem(position);
                        refreshUI(carListInfoList);
                        break;
                    case "NOT_EXIST":
                        Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    /**
     * 获得设备IdList
     *
     * @return
     */
    public List<String> getTermianlIdList() {
        List<String> terminalIdList = new ArrayList<>();
        for (int i = 0; i < carListInfoList.size(); i++) {
            terminalIdList.add(String.valueOf(carListInfoList.get(i).getId()));
        }
        return terminalIdList;
    }

    /**
     * 刷新列表和确认按钮 *
     */
    public void refreshList(List<CarListInfo> filterDateList) {
        adapter.updateListView(filterDateList);
    }

    private void refreshUI(List<CarListInfo> carListInfoList) {
        if (carListInfoList != null && carListInfoList.size() > 0) {
            withoutCarInfo_viewGroup.setVisibility(View.GONE);
            carList_listView.setVisibility(View.VISIBLE);
        } else {
            withoutCarInfo_viewGroup.setVisibility(View.VISIBLE);
            carList_listView.setVisibility(View.GONE);
        }
        searchCar_editText.setText("");
    }

    class CarListFragmentAdapter extends BaseAdapter {
        private List<CarListInfo> dataList;
        private String searchingString;

        CarListFragmentAdapter(List<CarListInfo> dataList) {
            this.dataList = dataList;
        }

        void setSearchingString(String searchingString) {
            this.searchingString = searchingString;
        }

        /**
         * 当ListView数据发生变化时,调用此方法来更新ListView
         */
        void updateListView(List<CarListInfo> filterDateList) {
            dataList = filterDateList;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public CarListInfo getItem(int i) {
            return dataList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            final ViewHolder viewHolder;
            final CarListInfo carListInfo = dataList.get(i);
            if (view == null) {
                viewHolder = new ViewHolder();
                view = getActivity().getLayoutInflater().inflate(R.layout.adapter_car_list, null);
                viewHolder.carOnlineStatus_imageView = (ImageView) view.findViewById(R.id.fragment_car_list_online_status_pic);
                viewHolder.carOnlineStatus_textView = (TextView) view.findViewById(R.id.fragment_car_list_online_status_text);
                viewHolder.carName_textView = (TextView) view.findViewById(R.id.fragment_car_list_car_name);
                viewHolder.carLicensePlate_textView = (TextView) view.findViewById(R.id.fragment_car_list_car_license_plate);
                viewHolder.itemDelete_button = (ImageButton) view.findViewById(R.id.item_delete_btn);
                viewHolder.itemCarList_linearLayout = (LinearLayout) view.findViewById(R.id.item_car_list_ll);
                viewHolder.swipeMenu_layout = (SwipeMenuLayout) view.findViewById(R.id.swipe_menu_layout);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }
            // 设置车辆名称
            String carName = carListInfo.getDisplayid();
            viewHolder.carName_textView.setText(carName);
            // 设置车辆车牌号
            String carLicensePlate = carListInfo.getCarId();
            viewHolder.carLicensePlate_textView.setText(carLicensePlate);
            // 设置车辆在线状态
            Boolean carOnlineStatus = carListInfo.getOnline();
            // 设置车辆在线状态图片
            if (carOnlineStatus) {
                viewHolder.carOnlineStatus_textView.setText(R.string.online);
                viewHolder.carOnlineStatus_imageView.setBackgroundResource(R.mipmap.fragment_car_list_motorcycle_online);
            } else {
                viewHolder.carOnlineStatus_textView.setText(R.string.offline);
                viewHolder.carOnlineStatus_imageView.setBackgroundResource(R.mipmap.fragment_car_list_motorcycle_offline);
            }

            if (!TextUtils.isEmpty(searchingString)) {
                int phonePosition = carName.indexOf(searchingString);
                boolean isSearch = carName.contains(searchingString);
                if (isSearch) {
                    SpannableStringBuilder builder = new SpannableStringBuilder(carName);
                    ForegroundColorSpan colorSpan = new ForegroundColorSpan(MainApp.getInstance()
                            .getResources().getColor(R.color.red));
                    builder.setSpan(colorSpan, phonePosition, phonePosition + searchingString.length(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    viewHolder.carName_textView.setText(builder);
                }
                int namePosition = carLicensePlate.indexOf(searchingString);
                boolean nameIsSearch = carLicensePlate.contains(searchingString);
                if (nameIsSearch) {
                    SpannableStringBuilder builder = new SpannableStringBuilder(carLicensePlate);
                    ForegroundColorSpan colorSpan = new ForegroundColorSpan(MainApp.getInstance()
                            .getResources().getColor(R.color.red));
                    builder.setSpan(colorSpan, namePosition, namePosition + searchingString.length(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    viewHolder.carLicensePlate_textView.setText(builder);
                }
            }
            //侧滑出的删除按钮监听
            viewHolder.itemDelete_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final UnBindCarDialog unBindCarDialog = new UnBindCarDialog();
                    unBindCarDialog.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //确定按钮监听
                            //解除绑定
                            unbindTerminal(carListInfo.getSimNum(), i);
                            unBindCarDialog.dismiss();
                        }
                    });
                    unBindCarDialog.show(getActivity().getFragmentManager(), "");
                    viewHolder.swipeMenu_layout.quickClose();
                }
            });
            //车辆列表Item监听
            viewHolder.itemCarList_linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), CarActivity.class);
                    CarListInfo carListInfo = adapter.getItem(i);
                    intent.putExtra(Constant.TerminalInfo.terminalId, carListInfo.getId());
                    startActivity(intent);
                }
            });
            return view;
        }

        public void removeItem(int position) {
            dataList.remove(position);
            notifyDataSetChanged();
        }
    }

    class ViewHolder {
        ImageView carOnlineStatus_imageView;
        TextView carOnlineStatus_textView;
        TextView carName_textView;
        TextView carLicensePlate_textView;
        ImageButton itemDelete_button;
        LinearLayout itemCarList_linearLayout;
        SwipeMenuLayout swipeMenu_layout;
    }
}
